package com.itheima.dao.impl;

import com.itheima.dao.BaseTeacherDao;
import com.itheima.domain.Teacher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class TeacherDao implements BaseTeacherDao {
    private static ArrayList<Teacher> list = new ArrayList<>();
    private static final Logger LOGGER = LoggerFactory.getLogger(TeacherDao.class);
    static {
        reLoad();
        System.out.println("========== loading ==========");
    }

    @Override
    public boolean addTeacher(Teacher teacher) {
        if (getIndex(teacher.getId()) != -1){
            return false;
        }
        list.add(teacher);
        reSave();
        return true;
    }

    @Override
    public List<Teacher> findAllTeacher() {
        return list;
    }

    @Override
    public boolean deleteTeacher(String delId) {
        int index = getIndex(delId);
        if (index != -1){
            list.remove(index);
            return true;
        }
        return false;
    }

    @Override
    public boolean updateTeacher(String updateId, Teacher newTeacher) {
        int index = getIndex(updateId);
        if (index == -1){
            return false;
        }
        list.set(index,newTeacher);
        reSave();
        return true;
    }

    @Override
    public int getIndex(String id) {
        //1. 标记位: 先假设要查找的学号不存在
        int index = -1;
        //2. 遍历容器
        for (int i = 0; i < list.size(); i++) {
            //取出数组中每一个索引位置的元素
            Teacher teacher = list.get(i);

            //判断当前索引位置的元素的学号与要查找的学号是否相同
            if (teacher != null && teacher.getId().equals(id)) {
                index = i;      //相同则记录当前学生对象的索引位置
                break;
            }
        }

        //3. 返回index
        return index;
    }

    //封装一个方法将数据加载进内存
    private static ArrayList<Teacher> reLoad(){
        //创建反序列化流
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("server//teacher.txt")));
            list = (ArrayList<Teacher>) ois.readObject();
            ois.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
          //  e.printStackTrace();
            LOGGER.error("序列化流时,出现异常:" + e.getMessage());
        }
        return null;
    }


    //封装一个方法将数据永久化保存
    private void reSave(){
        try {
            //创建序列化流
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("server//teacher.txt")));
            oos.writeObject(list);
            oos.close();
        } catch (IOException e) {
            //e.printStackTrace();
            LOGGER.error("反序列化流时,出现异常:" + e.getMessage());
        }
    }
}
